/**
 * 
 */
package travibot.ui.gui.forms;

import java.net.URL;
import java.util.Map;
import java.util.Set;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;

import travibot.engine.GameSessionFacade;
import travibot.engine.Session;
import travibot.engine.TaskQueue;
import travibot.model.Village;
import travibot.resource.ResourceHelper;
import travibot.ui.gui.StatusNotification;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
/**
 * @author Petr Macek
 * 
 */
public class TraviBotShell implements MainForm {

	private Listener autoBehaviourListener = new Listener() {
		public void handleEvent(Event event) {

			if (session != null) {
				if (Session.State.CONNECTED == session.getState()) {
					session.stop();
				} else if (Session.State.STOPPED == session.getState()) {
					session.start();
				}
			}
		}
	};
	private Listener connectionListener = new Listener() {
		public void handleEvent(Event event) {

			if (session != null) {
				if (Session.State.CONNECTED == session.getState()) {
					session.disconnect();
				} else if (Session.State.DISCONNECTED == session.getState()) {
					session.connect();
				}
			}
		}
	};
	private CompositeForm buildings = null;
	private TabItem buildingsTabItem = null;
	private TabFolder centerTabFolder = null;
	private CompositeForm cityList = null;	
	private CompositeForm fields = null;
	private TabItem filedsTabItem = null;
	private Session session = null;
	private Shell sShell = null; // @jve:decl-index=0:visual-constraint="3,10"	
	private StatusBar statusBar = null;
	private CompositeForm tasks = null;
	private TabItem tasksTabItem = null;
	private ToolBar toolBar = null;
	private ImageRegistry imageRegistry = null;
	private GameSessionFacade gameSession;

	/**
	 * This method initializes centerTabFolder
	 * 
	 */
	private void createCenterTabFolder() {

		GridData gridData2 = new GridData();
		gridData2.horizontalAlignment = GridData.FILL;
		gridData2.grabExcessHorizontalSpace = true;
		gridData2.grabExcessVerticalSpace = true;
		gridData2.verticalAlignment = GridData.FILL;
		centerTabFolder = new TabFolder(sShell, SWT.NONE);
		centerTabFolder.setLayoutData(gridData2);
	}

	/**
	 * This method initializes testComposite
	 * 
	 */
	private void createCityList() {
		cityList = new CityList(sShell, SWT.NONE);
		GridData gridData = new GridData();
		gridData.horizontalAlignment = GridData.END;
		gridData.grabExcessVerticalSpace = true;
		gridData.verticalAlignment = GridData.FILL;

		GridLayout gridLayout = new GridLayout();
		gridLayout.horizontalSpacing = 0;
		gridLayout.marginWidth = 0;
		gridLayout.marginHeight = 0;
		gridLayout.verticalSpacing = 0;

		((Composite) cityList).setLayout(gridLayout);
		((Composite) cityList).setLayoutData(gridData);
		cityList.setMainForm(this);		
	}

	/**
	 * This method initializes sShell
	 * 
	 * @param display
	 */
	public void createSShell(Display display) {

		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		sShell = new Shell(display);
		sShell.setText("TraviBot");		
		createToolBar();
		createCenterTabFolder();
		sShell.setLayout(gridLayout);
		createCityList();
		createStatusBar();
		sShell.setSize(new Point(640, 480));
		sShell.addDisposeListener(new DisposeListener(){
			public void widgetDisposed(org.eclipse.swt.events.DisposeEvent arg0) {
				session.dispose();
			}			
		});		
	}

	/**
	 * This method initializes status
	 * 
	 */
	private void createStatusBar() {

		GridData statusBarLData = new GridData();
		statusBarLData.horizontalAlignment = GridData.FILL;
		statusBarLData.horizontalSpan = 2;
		statusBarLData.verticalAlignment = GridData.END;
		statusBarLData.grabExcessHorizontalSpace = true;

		statusBar = new StatusBar(sShell, SWT.NONE);
		statusBar.setSize(new Point(600, 48));
		statusBar.setLayoutData(statusBarLData);

	}

	/**
	 * This method initializes toolBar
	 * 
	 */
	private void createToolBar() {

		GridData gridData = new GridData();
		gridData.horizontalAlignment = GridData.FILL;
		gridData.grabExcessHorizontalSpace = true;
		gridData.horizontalSpan = 2;
		gridData.verticalAlignment = GridData.CENTER;
		toolBar = new ToolBar(sShell, SWT.NONE);
		toolBar.setLayoutData(gridData);
		
		ToolItem btnConnectDisconncet = new ToolItem(toolBar, SWT.PUSH);
		btnConnectDisconncet.setText("Connect/Disconnect");
		btnConnectDisconncet.addListener(SWT.Selection, connectionListener);
		
		ToolItem btnAutoBehaviour = new ToolItem(toolBar, SWT.PUSH);
		btnAutoBehaviour.setText("Auto mode");
		btnAutoBehaviour.addListener(SWT.Selection, autoBehaviourListener);
	}
	
	private void loadImages() {

        imageRegistry = new ImageRegistry(sShell.getDisplay());

        Map<String, String> iconNames = ResourceHelper.getKeyValues("images", "image");
        if (iconNames != null && iconNames.size() > 0) {
            Set<String> keys = iconNames.keySet();
            for (String key : keys) {
                URL url = this.getClass().getResource(iconNames.get(key));
                imageRegistry.put(key, ImageDescriptor.createFromURL(url));
            }
        }
    }

	public Shell getSShell() {

		return sShell;
	}

	public void setSession(Session session) {

		this.session = session;

	}

	public void updateBuildingsTab(final Village village) {

		Runnable r = new Runnable() {

			public void run() {

				if (null == buildings) {
					buildings = new Buildings(centerTabFolder, SWT.NONE);
					buildings.setImageRegistry(getImageRegistry());
					buildingsTabItem = new TabItem(centerTabFolder, SWT.NONE);
					buildingsTabItem.setControl((Composite) buildings);
					buildingsTabItem.setText("Buildings");
				}

				buildings.setInput(village);
			}
		};
		sShell.getDisplay().asyncExec(r);
	}

	public void updateCityList(final Session session) {

		Runnable r = new Runnable() {
			public void run() {
				cityList.setInput(session);
			}
		};
		sShell.getDisplay().asyncExec(r);
	}

	public void updateFieldsTab(final Village village) {

		Runnable r = new Runnable() {
			public void run() {

				if (null == fields) {
					createFields();			
				}

				fields.setInput(village);				
			}
		};
		sShell.getDisplay().asyncExec(r);
	}
	
	private void createFields(){
	    fields = new Fields(centerTabFolder, SWT.NONE);
        fields.setImageRegistry(getImageRegistry());
        filedsTabItem = new TabItem(centerTabFolder, SWT.NONE);
        filedsTabItem.setControl((Composite) fields);
        filedsTabItem.setText("Fields");
        fields.setMainForm(this);        
    }
	
	public void updateStatusBar(final StatusNotification statusNotification) {

		Runnable r = new Runnable() {
			public void run() {
				statusBar.showNotification(statusNotification);
			}
		};
		sShell.getDisplay().asyncExec(r);
	}

	public void updateTasksTab(final TaskQueue queue) {

		Runnable r = new Runnable() {
			public void run() {

				if (null == tasks) {
					tasks = new TaskList(centerTabFolder, SWT.NONE);
					tasks.setImageRegistry(getImageRegistry());
					tasksTabItem = new TabItem(centerTabFolder, SWT.NONE);
					tasksTabItem.setControl((Composite) tasks);
					tasksTabItem.setText("Tasks");
				}

				tasks.setInput(queue);
			}
		};
		sShell.getDisplay().asyncExec(r);
	}

    public ImageRegistry getImageRegistry() {
        if(imageRegistry == null){
            loadImages();
        }
        return imageRegistry;
    }

    public void setGameSession(GameSessionFacade gameSession) {

       this.gameSession = gameSession;
    }

    public GameSessionFacade getGameSession() {

        return gameSession;
    }
	
	
}
